<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>获取元素位置-动起来</title>
    <style>
        .big{
            width: 800px;
            height: 600px;
            border: 3px solid black;
            margin: 0 auto;
            position: relative;
        }
        .one{
            width: 100px;
            height: 100px;
            border: 3px solid red;
            position: absolute;
            left:0px;
            top:0px
        }
    </style>
</head>
<body>
<button onclick="show()">打印数据</button>
<button onclick="moveLeft()">向左</button>
<button onclick="moveRight()">向右</button>
<button onclick="moveUp()">向上</button>
<button onclick="moveDown()">向下</button>
<div id="big" class="big">
    <div id="one" class="one"></div>
</div>
<script>
    document.addEventListener("keypress",function (event){
        console.log(event.key)
        if(event.key == 'w'){
            moveUp()
        }else if(event.key == 's'){
            moveDown()
        }else if(event.key == 'a'){
            moveLeft()
        }else if(event.key == 'd'){
            moveRight()
        }
    })


    function moveUp(){
        const one = document.getElementById("one")
        let top = parseInt(window.getComputedStyle(one).top)
        if(top <= 0){
            return
        }
        top -= 20
        one.style.top = top+'px'
    }
    function moveDown(){
        const one = document.getElementById("one")
        let top = parseInt(window.getComputedStyle(one).top)
        if(top >= 700){
            return
        }
        top += 20
        one.style.top = top+'px'
    }
    function moveRight(){
        const one = document.getElementById("one")
        let left = parseInt(window.getComputedStyle(one).left)
        if(left >= 700){
            return
        }
        left += 20
        one.style.left = left+'px'
    }
    function moveLeft(){
        const one = document.getElementById("one")
        let left = parseInt(window.getComputedStyle(one).left)
        if(left <= 0){
            return
        }
        left -= 20
        one.style.left = left+'px'
    }

    function show(){
        const one = document.getElementById("one")
        console.log("offsetHeight",one.offsetHeight)
        console.log("offsetWidth",one.offsetWidth)
        console.log("offsetLeft",one.offsetLeft)
        console.log("offsetTop",one.offsetTop)
        console.log("offsetParent",one.offsetParent)
    }

</script>
</body>
</html>